﻿Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized

Namespace NEvoWeb.Modules.NB_Store.Gateway

    Public Class GatewayCMCIC
        Inherits GatewayInterface


        Public Overrides Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
            Dim strHTML As String = ""
            Dim objSCtrl As New SettingsController
            Dim objSInfo As NB_Store_SettingsInfo
            'get the gateway settings from the NB_Store settings table
            objSInfo = objSCtrl.GetSetting(PortalID, "CMCIC.gateway", Lang)
            If Not objSInfo Is Nothing Then
                'Move the xml format settingn into the a hashtable so we can use it easily.
                Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)
                'Build Html to display the payment button.
                strHTML = "<input type=""IMAGE"" name=""CMCICGATEWAY"" border=""0"" SRC=""" & setParams("ButtonImageURL") & """/>"
            End If
            Return strHTML
        End Function


        Public Overrides Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)
            Try
                UpdateLog("AUTO START - OLD")

                'Dim objSCtrl As New SettingsController
                'Dim objOCtrl As New OrderController
                'Dim objPCtrl As New ProductController
                'Dim objOInfo As NB_Store_OrdersInfo
                'Dim rtnMsg As String = "version=2" & vbLf & "cdr=1" & vbLf

                '' ------------------------------------------------------------------------
                '' In this case the payment provider passes back data via form POST.
                '' Get the data we need.
                'Dim textelibre As String = ""
                'Dim CMCICStoreOrderID As Integer = 0
                'Dim CMCICCartID As String = ""
                'Dim CMCICClientLang As String = ""
                'If Not Request.Form("texte-libre") Is Nothing Then
                '    textelibre = Request.Form("texte-libre")
                '    If textelibre <> "" Then

                '        Dim strData As String() = textelibre.Split(";"c)
                '        CMCICStoreOrderID = CInt(strData(0))
                '        CMCICCartID = strData(1)
                '        CMCICClientLang = strData(2)
                '        ' ------------------------------------------------------------------------


                '        'Log response data so we can tell if the auto response has worked.
                '        UpdateLog("AUTO = OrderID:" & CMCICStoreOrderID & " textelibre = " & textelibre)

                '        'clear cart parameters, this is not strictly needed but does help tidy things up.
                '        Dim objCCtrl As New CartController
                '        Dim objCInfo As NB_Store_CartInfo = objCCtrl.GetCart(CMCICCartID)
                '        If Not objCInfo Is Nothing Then
                '            objCInfo.BankTransID = -1
                '            objCInfo.BankHtmlRedirect = ""
                '            objCCtrl.UpdateObjCart(objCInfo)
                '        End If

                '        ' ------------------------------------------------------------------------
                '        ' This section updates the order.
                '        objOInfo = objOCtrl.GetOrder(CMCICStoreOrderID)

                '        If Not objOInfo Is Nothing Then
                '            Dim CMCICStatusCode As String = getStatusCode(objOInfo, Request)

                '            If CMCICStatusCode = "02" Then
                '                rtnMsg = "version=2" & Environment.NewLine & "cdr=1"
                '            Else
                '                rtnMsg = "version=2" & Environment.NewLine & "cdr=0"
                '            End If
                '            'Log response data so we can tell if the auto response has worked.
                '            UpdateLog("AUTO Status:" & CMCICStatusCode)

                '            'check that the order is valid. (Not yet been processed)
                '            If Not objOInfo.OrderIsPlaced Then
                '                If CMCICStatusCode = "00" Then ' Stauts return "00" is payment successful
                '                    ' check if order has already been processed
                '                    If Not objOInfo.OrderIsPlaced Then
                '                        'remove qty in trans
                '                        objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                '                        'set order status to Payed
                '                        objOInfo.OrderStatusID = 40
                '                        Dim UsrID As Integer = objOInfo.UserID
                '                        If UsrID = -1 Then UsrID = 0
                '                        objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UsrID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                '                        objOInfo.OrderIsPlaced = True
                '                        objOCtrl.UpdateObjOrder(objOInfo)

                '                        'Send email confirmation
                '                        SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", CMCICClientLang)
                '                        SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")
                '                    End If
                '                Else
                '                    'check if order has already been cancelled
                '                    If Not objOInfo.OrderStatusID = 30 Then
                '                        'remove qty in trans
                '                        objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                '                        'set order status to cancelled
                '                        objOInfo.OrderStatusID = 30
                '                        objOCtrl.UpdateObjOrder(objOInfo)
                '                    End If
                '                End If
                '            End If
                '        End If

                '    End If
                'End If

                'HttpContext.Current.Response.Clear()
                ''HttpContext.Current.Response.ContentType = "text/plain"
                ''HttpContext.Current.Response.StatusCode = 200
                ''HttpContext.Current.Response.Write(rtnMsg)
                ''HttpContext.Current.Response.Flush()
                ''HttpContext.Current.Response.Close()

                'HttpContext.Current.Response.ContentType = "text/plain"
                'HttpContext.Current.Response.CacheControl = "no-cache"
                'HttpContext.Current.Response.Expires = -1

                'Dim Reponse As String = "version=2" & Environment.NewLine & "cdr=" & "0"

                'HttpContext.Current.Response.Write(Reponse)
                'HttpContext.Current.Response.Flush()
                ''HttpContext.Current.Response.End()
                'HttpContext.Current.Response.Close()

            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                SendEmailToAdministrator(PortalID, "CMCIC AutoReturn ERROR", ex.ToString)
            End Try
        End Sub

        Public Overrides Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest) As String
            Dim objSCtrl As New SettingsController
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim objOInfo As NB_Store_OrdersInfo
            Dim objSInfo As NB_Store_SettingsTextInfo
            Dim ordID As Integer = -1
            Dim rtnMsg As String = ""

            'Get the order id back from the url.
            ordID = Request.QueryString("ordID")

            'set rtnMsg to security warning message.
            objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentSECURITY.text", GetCurrentCulture)
            rtnMsg = objSInfo.SettingText
            If IsNumeric(ordID) Then
                objOInfo = objOCtrl.GetOrder(ordID)
                If Not objOInfo Is Nothing Then
                    'Here we make sure that the user  trying to view the order is the same as the user that placed the order.
                    'If this is not the case, then we want to display the security warning.
                    If objOInfo.UserID = UserID Then

                        'The user is OK, so continue to pocess the order.
                        '  In most circustances the order will already have been processed by the autoresponse function.
                        '  However it's always good practise to check this and process the order if it has not been done already.
                        '  If the payment provider does not support AutoResponse, then you must do the order processing here.

                        Select Case UCase(Request.QueryString("CMCICExit"))
                            Case "CANCEL"
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced Then
                                    'check if order has already been cancelled
                                    If Not objOInfo.OrderStatusID = 30 Then
                                        'remove qty in trans
                                        objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                        'set order status to cancelled
                                        objOInfo.OrderStatusID = 30
                                        objOCtrl.UpdateObjOrder(objOInfo)
                                    End If
                                    'set Cancel order message
                                    objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentFAIL.text", GetCurrentCulture)
                                    rtnMsg = objSInfo.SettingText
                                End If
                            Case "RETURN"
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced Then
                                    'remove qty in trans
                                    objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                                    'set order status to Payed
                                    objOInfo.OrderStatusID = 45
                                    objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UserID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                    objOInfo.OrderIsPlaced = True
                                    objOCtrl.UpdateObjOrder(objOInfo)
                                    'because in this case the order should have been processed by the autoresponse, but has not.
                                    'We're therefore going to send a payment unverified email to the client and manager.
                                    'This just tells the manager to check the payment has actually gone through.
                                    SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentunverified.email")
                                End If
                                'set completed order message
                                objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentOK.text", GetCurrentCulture)
                                rtnMsg = objSInfo.SettingText
                            Case Else
                                ' break
                        End Select

                        'Do Token Replacement
                        Dim objTR As New TokenStoreReplace(objOInfo, GetMerchantCulture(PortalID))
                        rtnMsg = objTR.DoTokenReplace(rtnMsg)
                    End If
                End If
            End If
            Return rtnMsg
        End Function


        Public Overrides Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
            'test if button has been clicked
            If Not Request.Form.Item("CMCICGATEWAY.x") Is Nothing Then
                Return True
            Else
                Return False
            End If
        End Function

        Public Overrides Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)
            Dim RPost As New RemotePost ' RemotePost class from NB_Store, this generates the re-direct html required.

            Dim strXMLSettings As String = GetStoreSetting(PortalID, "CMCIC.gateway", Lang)

            If strXMLSettings <> "" Then
                Dim setParams As Hashtable = ParseGateway(strXMLSettings)

                'Get the order we want to pay for.
                Dim objOCtrl As New OrderController
                Dim oInfo As NB_Store_OrdersInfo = objOCtrl.GetOrder(OrderID)
                If Not oInfo Is Nothing Then

                    Dim objCMCIC As CMCIC = New CMCIC(oInfo)

                    Dim oBInfo As NB_Store_AddressInfo
                    oBInfo = objOCtrl.GetOrderAddress(oInfo.BillingAddressID)

                    Dim OrderTotal As String = oInfo.Total.ToString("0.00")
                    OrderTotal = System.Text.RegularExpressions.Regex.Replace(OrderTotal, "[^0-9]", "")

                    RPost.Url = objCMCIC.sUrlPaiement

                    RPost.Add("version", objCMCIC.sVersion)
                    RPost.Add("TPE", objCMCIC.sNumero)
                    RPost.Add("date", objCMCIC.sDate)
                    RPost.Add("montant", objCMCIC.sMontantForm)
                    RPost.Add("reference", objCMCIC.sReference)
                    RPost.Add("MAC", objCMCIC.sMAC)
                    RPost.Add("url_retour", objCMCIC.sUrlKo)
                    RPost.Add("url_retour_ok", objCMCIC.sUrlOk)
                    RPost.Add("url_retour_err", objCMCIC.sUrlKo)
                    RPost.Add("lgue", objCMCIC.sLangueForm)
                    RPost.Add("societe", objCMCIC.sCodeSociete)
                    RPost.Add("texte-libre", objCMCIC.sTexteLibre)
                    RPost.Add("mail", objCMCIC.sEmail)

                    RPost.Add("nbrech", "")
                    RPost.Add("dateech1", "")
                    RPost.Add("montantech1", "")
                    RPost.Add("dateech2", "")
                    RPost.Add("montantech2", "")
                    RPost.Add("dateech3", "")
                    RPost.Add("montantech3", "")
                    RPost.Add("dateech4", "")
                    RPost.Add("montantech4", "")

                    Dim gatewayImg As String = GetStoreSetting(PortalID, "gateway.loadimage", "None")

                    'update stock transaction in progress
                    Dim objPCtrl As New ProductController
                    objPCtrl.UpdateModelQtyTrans(oInfo.OrderID)
                    'set order status to redirect to bank
                    oInfo.OrderStatusID = 20
                    objOCtrl.UpdateObjOrder(oInfo)

                    '-------------------------------------------------
                    'We are now going to save the re-direct html into the cart data on the database.
                    ' This is because the actual re-direct is done by the checkout module, when it loads.
                    'Get the cart data from the database.
                    Dim objCInfo As NB_Store_CartInfo = CurrentCart.GetCurrentCart(PortalID)
                    'Build and assign the re-direct html to the cart.
                    objCInfo.BankHtmlRedirect = RPost.GetPostHtml(gatewayImg)
                    'Save this data on the cart.
                    CurrentCart.Save(objCInfo)
                    '-------------------------------------------------
                    'Do a log statement of the html created, so we have a trace of what data has been passed.
                    UpdateLog("CMCIC HTML = " & objCInfo.BankHtmlRedirect)

                End If
            End If
        End Sub

        Public Function createSettingsTable(ByVal SettingsParams As String) As Hashtable
            Return ParseGateway(SettingsParams)
        End Function

        Public Shared Function getStatusCode(ByVal oInfo As NEvoWeb.Modules.NB_Store.NB_Store_OrdersInfo, ByVal Request As HttpRequest) As String

            Dim montant As String = ""
            Dim reference As String = ""
            Dim MAC As String = ""
            Dim TexteLibre As String = ""
            Dim CodeRetour As String = ""
            Dim dateConfirmation As String = ""
            Dim Cvx As String = ""
            Dim Vld As String = ""
            Dim Brand As String = ""
            Dim Status3DS As String = ""
            Dim NumAuto As String = ""
            Dim MotifRefus As String = ""
            Dim OrigineCB As String = ""
            Dim BinCB As String = ""
            Dim HPanCB As String = ""
            Dim IPClient As String = ""
            Dim OrigineTr As String = ""
            Dim VeRes As String = ""
            Dim PaRes As String = ""
            Dim MontantEch As String = ""
            Dim sResult As String = ""

            Dim sDataToValidate As String = ""

            Dim objCMCIC As CMCIC = New CMCIC(oInfo)

            'Dim oTpe As New CMCIC_Tpe(oInfo)
            'Dim oHmac As New CMCIC_Hmac(oTpe)

            montant &= Request.Form("montant")
            reference &= Request.Form("reference")
            MAC &= Request.Form("MAC")
            TexteLibre &= Request.Form("texte-libre")
            CodeRetour &= Request.Form("code-retour")
            dateConfirmation &= Request.Form("date")
            Cvx &= Request.Form("cvx")
            Vld &= Request.Form("vld")
            Brand &= Request.Form("brand")
            Status3DS &= Request.Form("status3ds")
            NumAuto &= Request.Form("numauto")
            MotifRefus &= Request.Form("motifrefus")
            OrigineCB &= Request.Form("originecb")
            BinCB &= Request.Form("bincb")
            HPanCB &= Request.Form("hpancb")
            IPClient &= Request.Form("ipclient")
            OrigineTr &= Request.Form("originetr")
            VeRes &= Request.Form("veres")
            PaRes &= Request.Form("pares")
            MontantEch &= Request.Form("montantech")


            sDataToValidate = objCMCIC.sNumero & "*" & dateConfirmation & "*" & montant & "*" & reference & "*" & TexteLibre & "*" & objCMCIC.sVersion & "*" & CodeRetour & "*"
            sDataToValidate &= Cvx & "*" & Vld & "*" & Brand & "*" & Status3DS & "*" & NumAuto & "*" & MotifRefus & "*"
            sDataToValidate &= OrigineCB & "*" & BinCB & "*" & HPanCB & "*" & IPClient & "*" & OrigineTr & "*" & VeRes & "*" & PaRes & "*"

            'UpdateLog("CMCIC CodeRetour = " & CodeRetour)
            'UpdateLog("CMCIC sDataToValidate = " & sDataToValidate & " MAC = " & objCMCIC.MacKey)

            If (objCMCIC.isValidHmac(sDataToValidate, MAC)) Then

                'UpdateLog("CMCIC Validated")
                sResult = "00"
                Select Case CodeRetour

                    Case "Annulation"

                        ' Payment has been refused
                        ' put your code here (email sending / Database update)
                        ' Attention : an authorization may still be delivered later
                        sResult = "01"
                    Case "payetest"

                        ' Payment has been accepted on the test server
                        ' put your code here (email sending / Database update)
                        sResult = "00"
                    Case "paiement"

                        ' Payment has been accepted on the productive server
                        ' put your code here (email sending / Database update)
                        sResult = "00"
                        '*** ONLY FOR MULTIPART PAYMENT ***'
                    Case "paiement_pf2"
                    Case "paiement_pf3"
                    Case "paiement_pf4"
                        ' Payment has been accepted on the productive server for the part #N
                        ' return code is like paiement_pf[#N]
                        ' put your code here (email sending / Database update)
                        ' You have the amount of the payment part in MontantEch

                    Case "Annulation_pf2"
                    Case "Annulation_pf3"
                    Case "Annulation_pf4"
                        ' Payment has been refused on the productive server for the part #N
                        ' return code is like Annulation_pf[#N]
                        ' put your code here (email sending / Database update)
                        ' You have the amount of the payment part in MontantEch


                End Select
            Else

                ' your code if the HMAC doesn't match

                sResult = "02"
            End If

            'UpdateLog("sResult = " & sResult)

            Return sResult
        End Function

    End Class


End Namespace
